package cn.corgy.registry.zk;


import cn.corgy.dto.RpcRequest;
import cn.corgy.enums.RpcErrorMessageEnum;
import cn.corgy.exception.RpcException;
import cn.corgy.extension.ExtensionLoader;
import cn.corgy.module.loadbalance.LoadBalance;
import cn.corgy.registry.ServiceDiscovery;
import cn.corgy.registry.zk.utils.CuratorUtil;
import cn.corgy.utils.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * 基于zookeeper的服务发现
 */
@Slf4j
public class ZkServiceDiscovery implements ServiceDiscovery {
    private final LoadBalance loadBalance;

    public ZkServiceDiscovery() {
        this.loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("loadBalance");
    }

    @Override
    public InetSocketAddress lookupService(RpcRequest rpcRequest) {
        String rpcServiceName = rpcRequest.getRpcServiceName();
        CuratorFramework zkClient = CuratorUtil.getZkClient();
        List<String> serviceUrlList = CuratorUtil.getChildrenNodes(zkClient, rpcServiceName);
        if (CollectionUtil.isEmpty(serviceUrlList)) {
            throw new RpcException(RpcErrorMessageEnum.SERVICE_CAN_NOT_BE_FOUND, rpcServiceName);
        }
        // 负载均衡 默认配置为一致性哈希
        return getInetSocketAddress(rpcRequest, serviceUrlList, loadBalance, log);
    }
}
